package com.mobile.collect.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: @Kongzue
 * Github: https://github.com/kongzue/
 * Homepage: http://kongzue.com/
 * Mail: myzcxhh@live.cn
 * CreateTime: 2019/4/24 15:51
 */
public class TableLayout extends RelativeLayout {
    
    public TableLayout(Context context) {
        super(context);
    }
    
    public TableLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public TableLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    
    private List<View> items;
    private int newHeight = 0;
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        
        refreshViews();
        Log.i(">>>", "newHeight: " + newHeight);
        setMeasuredDimension(getMeasuredWidth(), newHeight);//设置宽高
    }
    
    public void refreshViews() {
        newHeight = 0;
        int maxWidth = getMeasuredWidth();
        
        int itemWidth = maxWidth / 4;
        int itemHeight = itemWidth;
        
        items = new ArrayList<>();
        
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == VISIBLE) {
                LayoutParams lp = (LayoutParams) child.getLayoutParams();
                lp.width = itemWidth;
                lp.height = itemHeight;
                child.setLayoutParams(lp);
                items.add(getChildAt(i));
            }
        }
        
        newHeight = 0;
        if (items != null && !items.isEmpty()) {
            for (int i = 0; i < items.size(); i++) {
                View item = items.get(i);
                
                int n_x = 0;
                int n_y = 0;
                int o_y = 0;
                
                if (i != 0) {
                    n_x = (int) items.get(i - 1).getX() + itemWidth + 1;
                    n_y = (int) items.get(i - 1).getY() + itemHeight + 1;
                    o_y = (int) items.get(i - 1).getY();
                    
                    if (i % 4 == 0) {
                        n_x = 0;
                        o_y = n_y;
                        
                    } else {
                    
                    }
                }
                
                item.setY(o_y);
                item.setX(n_x);
                
                Log.i(">>>", "index: " + i + " x: " + item.getX() + " y: " + item.getY() + " w: " + item.getWidth() + " h: " + item.getHeight());
                
                newHeight = (int) (item.getY() + itemHeight);
            }
        }
    }
}
